﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.MachineStatus;
using HamcoWcs.DAL;
using HamcoWcs.Models.Charts;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Devices;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace HamcoWcs.Main.Controllers.Wcs
{
    public class MachineStateController : BasicController
    {

        private IMachineStateService _machineStateService;
        public MachineStateController(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger, IMachineStateService machineStateService) : base(logger, mapper, wcsDbContext)
        {
            _machineStateService = machineStateService;
        }

        [HttpPost]
        public IActionResult MachineStateQuery(MachineStateQueryModel model)
        {
            try
            {

                if (model.StartTime > model.EndTime)
                    throw new WarningException("选择的时间异常");
                if (model.StartTime?.AddYears(1) < model.EndTime)
                    throw new WarningException("选择的时间超过一年");
                if (model.MachineName.IsNullOrEmpty())
                {
                    throw new WarningException("选择设备异常");
                }
                if (model.Type.IsNullOrEmpty() && (model.StartTime == null || model.EndTime == null)) 
                {
                    throw new WarningException("筛选条件不对，请重新选择筛选条件");
                }
                var res = _machineStateService.SelectMachineState(model)?.OrderByDescending(x => x.MachineName).ToList();
                return Json(new ForeEndResult(res));
            }
            catch (HamcoWcs.Models.Exceptions.WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }
        public override string ControllerName => nameof(MachineStateController);
    }
}
